{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#  一、科大讯飞平台面部检测\n",
    "# A1：年龄识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'{\"code\":0,\"data\":{\"fileList\":[{\"label\":5,\"labels\":[5,12,6,4,11],\"name\":\"https://b-ssl.duitang.com/uploads/item/201804/30/20180430122053_vhnoq.thumb.700_0.jpg\",\"rate\":0.38880112767219543,\"rates\":[0.38880112767219543,0.31288543343544006,0.11238187551498413,0.086818166077137,0.0727187991142273],\"review\":false,\"tag\":\"Using url\"}],\"reviewCount\":0,\"topNStatistic\":[{\"count\":1,\"label\":5}]},\"desc\":\"success\",\"sid\":\"tup000246de@dx41a312ee62c51aba00\"}'\n"
     ]
    }
   ],
   "source": [
    "#万能不变的import调用\n",
    "import requests\n",
    "import json\n",
    "import time\n",
    "import hashlib\n",
    "import base64\n",
    "# 人脸特征分析年龄webapi接口地址\n",
    "URL = \"http://tupapi.xfyun.cn/v1/age\"\n",
    "APPID = \"5f927f95\"\n",
    "API_KEY = \"fe0555d29c785e63cca932a7611304d5\"\n",
    "ImageName = \"黄旼泫.jpg\"\n",
    "ImageUrl = \"https://b-ssl.duitang.com/uploads/item/201804/30/20180430122053_vhnoq.thumb.700_0.jpg\"\n",
    "# FilePath = r\"C:\\Users\\Admin\\Desktop\\1539656523.png\"\n",
    "\n",
    "def getHeader(image_name, image_url=None):\n",
    "    curTime = str(int(time.time()))\n",
    "    param = \"{\\\"image_name\\\":\\\"\" + image_name + \"\\\",\\\"image_url\\\":\\\"\" + image_url + \"\\\"}\"\n",
    "    paramBase64 = base64.b64encode(param.encode('utf-8'))\n",
    "    tmp = str(paramBase64, 'utf-8')\n",
    "\n",
    "    m2 = hashlib.md5()\n",
    "    m2.update((API_KEY + curTime + tmp).encode('utf-8'))\n",
    "    checkSum = m2.hexdigest()\n",
    "\n",
    "    header = {\n",
    "        'X-CurTime': curTime,\n",
    "        'X-Param': paramBase64,\n",
    "        'X-Appid': APPID,\n",
    "        'X-CheckSum': checkSum,\n",
    "    }\n",
    "    return header\n",
    "\n",
    "\n",
    "# def getBody(filePath):\n",
    "#     binfile = open(filePath, 'rb')\n",
    "#     data = binfile.read()\n",
    "#     return data\n",
    "\n",
    "\n",
    "r = requests.post(URL, headers=getHeader(ImageName, ImageUrl))\n",
    "print(r.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'dict'>\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'code': 0,\n",
       " 'data': {'fileList': [{'label': 5,\n",
       "    'labels': [5, 12, 6, 4, 11],\n",
       "    'name': 'https://b-ssl.duitang.com/uploads/item/201804/30/20180430122053_vhnoq.thumb.700_0.jpg',\n",
       "    'rate': 0.38880112767219543,\n",
       "    'rates': [0.38880112767219543,\n",
       "     0.31288543343544006,\n",
       "     0.11238187551498413,\n",
       "     0.086818166077137,\n",
       "     0.0727187991142273],\n",
       "    'review': False,\n",
       "    'tag': 'Using url'}],\n",
       "  'reviewCount': 0,\n",
       "  'topNStatistic': [{'count': 1, 'label': 5}]},\n",
       " 'desc': 'success',\n",
       " 'sid': 'tup000246de@dx41a312ee62c51aba00'}"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(type(r.json())) # 将json转化成python中的数据结构\n",
    "r.json()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#从科大讯飞平台的人脸特征分析-年龄api文档中寻找label值范围及对应年龄段，得知对应的age。\n",
    "-api文档：https://www.xfyun.cn/doc/face/face-feature-analysis/ageAPI.html#\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# A2：颜值识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import time\n",
    "import hashlib\n",
    "import base64\n",
    "\"\"\" \n",
    "  人脸特征分析颜值WebAPI接口调用示例接口文档(必看)：https://doc.xfyun.cn/rest_api/%E4%BA%BA%E8%84%B8%E7%89%B9%E5%BE%81%E5%88%86%E6%9E%90-%E9%A2%9C%E5%80%BC.html\n",
    "\n",
    "\"\"\"\n",
    "# 输入基本信息\n",
    "URL = \"http://tupapi.xfyun.cn/v1/face_score\"\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'{\"code\":0,\"data\":{\"fileList\":[{\"label\":0,\"name\":\"https://b-ssl.duitang.com/uploads/item/201804/30/20180430122053_vhnoq.thumb.700_0.jpg\",\"rate\":0.7687515616416931,\"review\":false,\"tag\":\"Using url\"}],\"reviewCount\":0,\"statistic\":[1,0,0,0,0,0]},\"desc\":\"success\",\"sid\":\"tup000246df@dx41a312ee62dd1aba00\"}'\n"
     ]
    }
   ],
   "source": [
    "r = requests.post(URL, headers=getHeader(ImageName, ImageUrl))\n",
    "print(r.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'dict'>\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'code': 0,\n",
       " 'data': {'fileList': [{'label': 0,\n",
       "    'name': 'https://b-ssl.duitang.com/uploads/item/201804/30/20180430122053_vhnoq.thumb.700_0.jpg',\n",
       "    'rate': 0.7687515616416931,\n",
       "    'review': False,\n",
       "    'tag': 'Using url'}],\n",
       "  'reviewCount': 0,\n",
       "  'statistic': [1, 0, 0, 0, 0, 0]},\n",
       " 'desc': 'success',\n",
       " 'sid': 'tup000246df@dx41a312ee62dd1aba00'}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(type(r.json())) # 将json转化成python中的数据结构\n",
    "r.json()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# A3：性别识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'{\"code\":0,\"data\":{\"fileList\":[{\"label\":0,\"name\":\"https://p3.ssl.qhimgs1.com/sdr/400__/t01d0e35abed8ea4ef9.jpg\",\"rate\":0.9324294328689575,\"review\":false,\"tag\":\"Using url\"}],\"reviewCount\":0,\"statistic\":[1,0,0,0]},\"desc\":\"success\",\"sid\":\"tup0002483c@dx091e12ee56f3000100\"}'\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import time\n",
    "import hashlib\n",
    "import base64\n",
    "\n",
    "\n",
    "URL = \"http://tupapi.xfyun.cn/v1/sex\"\n",
    "\n",
    "r = requests.post(URL, headers=getHeader(ImageName, ImageUrl))\n",
    "print(r.content)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'dict'>\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'code': 0,\n",
       " 'data': {'fileList': [{'label': 0,\n",
       "    'name': 'https://p3.ssl.qhimgs1.com/sdr/400__/t01d0e35abed8ea4ef9.jpg',\n",
       "    'rate': 0.9324294328689575,\n",
       "    'review': False,\n",
       "    'tag': 'Using url'}],\n",
       "  'reviewCount': 0,\n",
       "  'statistic': [1, 0, 0, 0]},\n",
       " 'desc': 'success',\n",
       " 'sid': 'tup0002483c@dx091e12ee56f3000100'}"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(type(r.json())) # 将json转化成python中的数据结构\n",
    "r.json()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# A4：表情识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'{\"code\":0,\"data\":{\"fileList\":[{\"label\":2,\"name\":\"https://b-ssl.duitang.com/uploads/item/201804/30/20180430122053_vhnoq.thumb.700_0.jpg\",\"rate\":0.6310632824897766,\"review\":true,\"tag\":\"Using url\"}],\"reviewCount\":1,\"statistic\":[0,0,1,0,0,0,0,0]},\"desc\":\"success\",\"sid\":\"tup00024841@dx091e12ee631b000100\"}'\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import time\n",
    "import hashlib\n",
    "import base64\n",
    "\n",
    "URL = \"http://tupapi.xfyun.cn/v1/expression\"\n",
    "\n",
    "\n",
    "r = requests.post(URL, headers=getHeader(ImageName, ImageUrl))\n",
    "print(r.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'dict'>\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'code': 0,\n",
       " 'data': {'fileList': [{'label': 2,\n",
       "    'name': 'https://b-ssl.duitang.com/uploads/item/201804/30/20180430122053_vhnoq.thumb.700_0.jpg',\n",
       "    'rate': 0.6310632824897766,\n",
       "    'review': True,\n",
       "    'tag': 'Using url'}],\n",
       "  'reviewCount': 1,\n",
       "  'statistic': [0, 0, 1, 0, 0, 0, 0, 0]},\n",
       " 'desc': 'success',\n",
       " 'sid': 'tup00024841@dx091e12ee631b000100'}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(type(r.json())) # 将json转化成python中的数据结构\n",
    "r.json()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 二、科大讯飞平台人脸集合\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Fri, 23 Oct 2020 17:47:50 GMT\n",
      "host: api.xf-yun.com\n",
      "date: Fri, 23 Oct 2020 17:47:50 GMT\n",
      "POST /v1/private/s67c9c78c HTTP/1.1\n",
      "api_key=\"e4fb144974332c95e49b17c6882dde6d\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"8JRt1wRfjtl+Vat5NNtQ7LsZKgGXwSWV0wPaiqPqps8=\"\n",
      "http://api.xf-yun.com/v1/private/s67c9c78c?host=api.xf-yun.com&date=Fri%2C+23+Oct+2020+17%3A47%3A50+GMT&authorization=YXBpX2tleT0iZTRmYjE0NDk3NDMzMmM5NWU0OWIxN2M2ODgyZGRlNmQiLCBhbGdvcml0aG09ImhtYWMtc2hhMjU2IiwgaGVhZGVycz0iaG9zdCBkYXRlIHJlcXVlc3QtbGluZSIsIHNpZ25hdHVyZT0iOEpSdDF3UmZqdGwrVmF0NU5OdFE3THNaS2dHWHdTV1Ywd1BhaXFQcXBzOD0i\n",
      "{'header': {'code': 0, 'message': 'success', 'sid': 'ase0007c0c9@hu1755692ebd40210882'}, 'payload': {'face_compare_result': {'compress': 'raw', 'encoding': 'utf8', 'format': 'json', 'text': 'ewoJInJldCIgOiAwLAoJInNjb3JlIiA6IDAuMjg3NjE1OTg0Njc4MjY4NDMKfQo='}}}\n",
      "{\n",
      "\t\"ret\" : 0,\n",
      "\t\"score\" : 0.28761598467826843\n",
      "}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 人脸比对 WebAPI 接口调用示例\n",
    "# 运行前：请先填写Appid、APIKey、APISecret以及图片路径\n",
    "# 接口文档（必看）：https://www.xfyun.cn/doc/face/xffaceComparisonRecg/API.html#\n",
    "\n",
    "from datetime import datetime\n",
    "from wsgiref.handlers import format_date_time\n",
    "from time import mktime\n",
    "import hashlib\n",
    "import base64\n",
    "import hmac\n",
    "from urllib.parse import urlencode\n",
    "import os\n",
    "import traceback\n",
    "import json\n",
    "import requests\n",
    "\n",
    "\n",
    "class AssembleHeaderException(Exception):\n",
    "    def __init__(self, msg):\n",
    "        self.message = msg\n",
    "\n",
    "\n",
    "class Url:\n",
    "    def __init__(this, host, path, schema):\n",
    "        this.host = host\n",
    "        this.path = path\n",
    "        this.schema = schema\n",
    "        pass\n",
    "\n",
    "\n",
    "# 进行sha256加密和base64编码\n",
    "def sha256base64(data):\n",
    "    sha256 = hashlib.sha256()\n",
    "    sha256.update(data)\n",
    "    digest = base64.b64encode(sha256.digest()).decode(encoding='utf-8')\n",
    "    return digest\n",
    "\n",
    "\n",
    "def parse_url(requset_url):\n",
    "    stidx = requset_url.index(\"://\")\n",
    "    host = requset_url[stidx + 3:]\n",
    "    schema = requset_url[:stidx + 3]\n",
    "    edidx = host.index(\"/\")\n",
    "    if edidx <= 0:\n",
    "        raise AssembleHeaderException(\"invalid request url:\" + requset_url)\n",
    "    path = host[edidx:]\n",
    "    host = host[:edidx]\n",
    "    u = Url(host, path, schema)\n",
    "    return u\n",
    "\n",
    "\n",
    "def assemble_ws_auth_url(requset_url, method=\"GET\", api_key=\"e4fb144974332c95e49b17c6882dde6d\", api_secret=\"0b86e0e672ab564f3c9835d71dc8c55e\"):\n",
    "    u = parse_url(requset_url)\n",
    "    host = u.host\n",
    "    path = u.path\n",
    "    now = datetime.now()\n",
    "    date = format_date_time(mktime(now.timetuple()))\n",
    "    print(date)\n",
    "    # date = \"Thu, 12 Dec 2019 01:57:27 GMT\"\n",
    "    signature_origin = \"host: {}\\ndate: {}\\n{} {} HTTP/1.1\".format(host, date, method, path)\n",
    "    print(signature_origin)\n",
    "    signature_sha = hmac.new(api_secret.encode('utf-8'), signature_origin.encode('utf-8'),\n",
    "                             digestmod=hashlib.sha256).digest()\n",
    "    signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')\n",
    "    authorization_origin = \"api_key=\\\"%s\\\", algorithm=\\\"%s\\\", headers=\\\"%s\\\", signature=\\\"%s\\\"\" % (\n",
    "        api_key, \"hmac-sha256\", \"host date request-line\", signature_sha)\n",
    "    authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')\n",
    "    print(authorization_origin)\n",
    "    values = {\n",
    "        \"host\": host,\n",
    "        \"date\": date,\n",
    "        \"authorization\": authorization\n",
    "    }\n",
    "\n",
    "    return requset_url + \"?\" + urlencode(values)\n",
    "\n",
    "def gen_body(appid, img1_path, img2_path, server_id):\n",
    "    with open(img1_path, 'rb') as f:\n",
    "        img1_data = f.read()\n",
    "    with open(img2_path, 'rb') as f:\n",
    "        img2_data = f.read()\n",
    "    body = {\n",
    "        \"header\": {\n",
    "            \"app_id\": appid,\n",
    "            \"status\": 3\n",
    "        },\n",
    "        \"parameter\": {\n",
    "            server_id: {\n",
    "                \"service_kind\": \"face_compare\",\n",
    "                \"face_compare_result\": {\n",
    "                    \"encoding\": \"utf8\",\n",
    "                    \"compress\": \"raw\",\n",
    "                    \"format\": \"json\"\n",
    "                }\n",
    "            }\n",
    "        },\n",
    "        \"payload\": {\n",
    "            \"input1\": {\n",
    "                \"encoding\": \"jpg\",\n",
    "                \"status\": 3,\n",
    "                \"image\": str(base64.b64encode(img1_data), 'utf-8')\n",
    "            },\n",
    "            \"input2\": {\n",
    "                \"encoding\": \"jpg\",\n",
    "                \"status\": 3,\n",
    "                \"image\": str(base64.b64encode(img2_data), 'utf-8')\n",
    "            }\n",
    "        }\n",
    "    }\n",
    "    return json.dumps(body)\n",
    "\n",
    "\n",
    "def run(appid, apikey, apisecret, img1_path, img2_path, server_id='s67c9c78c'):\n",
    "    url = 'http://api.xf-yun.com/v1/private/s67c9c78c'.format(server_id)\n",
    "    request_url = assemble_ws_auth_url(url, \"POST\", apikey, apisecret)\n",
    "    headers = {'content-type': \"application/json\", 'host': 'api.xf-yun.com', 'app_id': appid}\n",
    "    print(request_url)\n",
    "    response = requests.post(request_url, data=gen_body(appid, img1_path, img2_path, server_id), headers=headers)\n",
    "    resp_data = json.loads(response.content.decode('utf-8'))\n",
    "    print(resp_data)\n",
    "    print(base64.b64decode(resp_data['payload']['face_compare_result']['text']).decode())\n",
    "\n",
    "#请填写控制台获取的APPID、APISecret、APIKey以及要比对的图片路径\n",
    "if __name__ == '__main__':\n",
    "    run(\n",
    "        appid='5f927f95',\n",
    "        apisecret='0b86e0e672ab564f3c9835d71dc8c55e',\n",
    "        apikey='e4fb144974332c95e49b17c6882dde6d',\n",
    "        img1_path=r'C:\\Users\\86133\\Desktop\\洪知秀.jpg',\n",
    "        img2_path=r'C:\\Users\\86133\\Desktop\\黄旼泫.jpg',\n",
    "    )\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
